package App.OO.service.thread;

import App.Model.ArisuClientDB;
import App.Model.Interface.MessageType;
import App.Model.Tool.DosTool;
import App.Model.User;
import App.Model.message.Message;
import App.OO.ClientView.OOMainFrame;
import App.OO.ClientView.OOUserFrame;
import App.OO.service.OOTalkService;
import com.alibaba.fastjson.JSON;

import javax.swing.*;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

//监听服务器端的线程
public class CtoSThread extends Thread {
    public boolean notStop = true;//可能不安全
    private OOMainFrame ooMainFrame;
    private Socket socket;

    public CtoSThread(Socket socket, OOMainFrame mainFrame) {
        this.socket = socket;
        this.ooMainFrame = mainFrame;
    }

    @Override
    public void run() {
        //简单的打招呼
        String hello;
        LocalTime currentTime = LocalTime.now();
        if (currentTime.isBefore(LocalTime.of(12, 0))) {
            hello = "上午好 ";
        } else if (currentTime.isAfter(LocalTime.of(12, 0)) && currentTime.isBefore(LocalTime.of(18, 0))) {
            hello = "下午好 ";
        } else {
            hello = "晚上好 ";
        }
        hello += ooMainFrame.getUserId();
        ooMainFrame.setTextMessage(hello);

        //由于再循环外只能请求一次,故优先请求离线消息
        System.out.print("请求离线消息...");
        OOTalkService.getOfflineMessage(ooMainFrame.getUserId());
        //ooMainFrame.getLoginService().getUserAndOnlineList();

        //从服务器不断读取消息
        while (notStop) {
            try {
                ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
                Message message = (Message) inputStream.readObject();//无数据会阻塞,故不会产生性能损失
                if(message == null){//增加容错
                    continue;
                }
                String msgType = message.getMesType();
                //对message做处理
                //判断message的类型并对其处理
                if (msgType.equals(MessageType.MESSAGE_SET_ONLINE_LIST)) {       //后续更新为switch case
                    //在线列表信息的处理(具体数据具体处理)
                    System.out.println("接收数据: " + message.getContent());
                    ooMainFrame.updateUserList(message.getContent());
                } else if (msgType.equals(MessageType.MESSAGE_COMM_MSG) ||
                        msgType.equals(MessageType.MESSAGE_FILE_MSG_CONFORM) || //文件提醒
                        msgType.equals(MessageType.MESSAGE_COMM_MSG_MENTION)) { //消息提醒
                    //用户间交流(提醒与通话交流)
                    ooMainFrame.getMessageAtService(message);
                    String content = message.getSender() + " 对你说: " + message.getContent();
                    System.out.println(content);
                } else if (msgType.equals(MessageType.MESSAGE_COMM_MSG_ALL)) {
                    //用户间通话交流
                    String content = message.getSender() + " 对 大家 说: " + message.getContent();
                    System.out.println(content);
                } else if (msgType.equals(MessageType.MESSAGE_COMM_MSG_OFFLINE)) {
                    //离线消息与离线消息提醒处理
                    List<Message> messageList = message.getMessages();
                    List<String> userList = new ArrayList<>();//同时将这些发送的用户名返回给mainFrame供消息提示
                    if (messageList != null) {
                        System.out.println("成功请求离线消息");
                        for (Message mEach : messageList) {
                            String sender = mEach.getSender();
                            userList.add(sender);
                            if (ooMainFrame.getConversations().containsKey(sender)) {
                                ooMainFrame.getConversations()
                                        .get(sender)
                                        .add(mEach);
                            } else {
                                List<Message> mTemp = new ArrayList<>();
                                mTemp.add(mEach);
                                ooMainFrame.getConversations().put(sender, mTemp);
                            }
                        }
                        ooMainFrame.updateConformList(userList);//登陆时为离线通话提供提示
                    } else {
                        System.out.println("没有离线消息");
                    }
                    //再次向服务器返回请求:获取用户列表
                    Message mGetuserList = new Message();
                    mGetuserList.setSender(ooMainFrame.getUserId());
                    mGetuserList.setGetter("服务器");
                    mGetuserList.setMesType(MessageType.MESSAGE_GET_ONLINE_LIST);
                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    oos.writeObject(mGetuserList);
                    //测试用
//                    String content = "离线消息: " + message.getSender() + "对你说: " + message.getContent();
//                    System.out.println(content);
                } else if (msgType.equals(MessageType.MESSAGE_GET_MSG_NOW_USER)) {
                    //接收用户信息
                    System.out.println(message.getContent());
                    User oUser = JSON.parseObject(message.getContent(),User.class);

                    if(message.getFileBytes() != null){//将头像保存到本地(有就覆盖)
                        System.out.println("收到头像文件");
                        ArisuClientDB.putDataToHeaderImg(oUser.getUserId(),message.getFileBytes());
                        //ArisuClientDB.saveUserHeaderToFile(message.getFileBytes(),oUser.getHeaderUrl(),oUser.getUserId());
                    }
                    //根据该oUser生成对应的个性界面
                    //ImageIcon detailImg = ArisuClientDB.getUserHeaderAtFile(oUser.getUserId());
                    new OOUserFrame().ShowUserFrame(oUser,ooMainFrame.getUserId());
                    //new OOUserFrame().ShowUserFramePlus(oUser,ooMainFrame.getUserId());
                } else if (msgType.equals(MessageType.MESSAGE_FILE_MSG_GET_SUCCEED)) {
                    //获取文件成功的情况
                    JOptionPane.showMessageDialog
                            (null,"已接受" + DosTool.SplitFileName(message.getDest())
                                    , "提醒", JOptionPane.INFORMATION_MESSAGE);
                    System.out.println("收到了一封: " + message.getSender() + " 发送的文件到 " + message.getDest());
                    FileOutputStream fileOutputStream = new FileOutputStream(message.getDest());
                    fileOutputStream.write(message.getFileBytes());
                    fileOutputStream.close();
                } else if(msgType.equals(MessageType.MESSAGE_FILE_MSG_NOTGET_SUCCEED)){
                    //拒绝文件成功的情况
                    JOptionPane.showMessageDialog(null,"文件已拒收", "提醒", JOptionPane.INFORMATION_MESSAGE);
                } else if(msgType.equals(MessageType.MESSAGE_FILE_MSG_EXPIRE)) {
                    JOptionPane.showMessageDialog(null,"文件已过期", "错误", JOptionPane.WARNING_MESSAGE);
                } else if (msgType.equals(MessageType.MESSAGE_FILE_MSG)) {
                    //接受文件消息
                    System.out.println
                            ("收到了一封: " + message.getSender() + " 发送的文件" + message.getSrc() + "到 " + message.getDest());
//
//                    FileOutputStream fileOutputStream = new FileOutputStream(message.getDest());
//                    fileOutputStream.write(message.getFileBytes());
//                    fileOutputStream.close();
//                    System.out.println("保存成功");
                } else {//其他情况....
                    //可以接入服务器申请退出的消息,以使得服务器退出时用户程序能够安全退出
                    socket.close();
                    notStop = false;
                    break;
                }
            } catch (Exception e) {//模糊错误
                //e.printStackTrace();
            }
        }
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

}


